/**
 * 按照时间线进行客户端数据模拟.
 */
 export default {
  onContextBind: function (self, ctx) {
    this.auto = true;
    this.replay = true;
    this.time = 0;
    this.data = this.dataset();
    this.max = Object.keys(this.data.delta)
      .reduce((max, curr) => Math.max(max, parseInt(curr)), 0);

    // 1s 后开始自动播放
    if (this.auto) {
      setTimeout(() => self.setParameter('pStart', true, true), 1000);
    }
  },
  onContextUnbind: function (self, ctx) {
    this.onScriptStop(self, ctx);
  },
  onParameterUpdate: function (self, ctx, key, value) {
    if (key === 'pStop') {
      this.onScriptStop(self, ctx);
    }
    if (key === 'pReset') {
      this.onScriptStop(self, ctx);
      this.onScriptInit(self, ctx);
    }
    if (key === 'pStart') {
      this.onScriptStart(self, ctx);
    }
    if (key === 'pReplay') {
      this.onScriptStop(self, ctx);
      this.onScriptInit(self, ctx);
      this.onScriptStart(self, ctx);
    }
  },
  onScriptInit: function (self, ctx) {
    this.time = 0;
    this.data.init.forEach(row => this.execute(self, ctx, row));
  },
  onScriptStop: function (self, ctx) {
    if (this.loop) {
      clearInterval(this.loop);
      this.loop = null;
    }

    // 执行 Stop 逻辑
    this.data.stop.forEach(row => this.execute(self, ctx, row));
  },
  onScriptFinished: function (self, ctx) {
    // 停止当前循环
    this.onScriptStop(self, ctx);

    // 设置 1s 后重播
    if (this.replay) {
      setTimeout(() => self.setParameter('pReplay', true, true), 1000);
    }
  },
  onScriptStart: function (self, ctx) {
    this.loop = setInterval(() => {
      const rows = this.data.delta[this.time] || [];
      rows.forEach(row => this.execute(self, ctx, row));
      if (this.time === this.max) {
        debugger;
        this.onScriptFinished(self, ctx);
      } else {
        this.time++;
      }
    }, 1000);
  },
  execute: function (self, ctx, row) {
    const scene = ctx.SCENE_MANAGER.active;
    const object = scene.of(row.object);
    if (object) {
      object.setParameter(row.key, row.value, row.force || false);
    }
  },
  dataset: function () {
    return {
      init: [
      ],
      delta: {
        1: [{ object: '内饰三线输送线（快速1）', key: 'pEnabled', value: 1, force: true }],
      },
      stop: [
      ],
    }
  },
}